import 'package:bilibili/navigator/hi_navigator.dart';
import 'package:bilibili/page/favorite_page.dart';
import 'package:bilibili/page/home_page.dart';
import 'package:bilibili/page/profile_page.dart';
import 'package:bilibili/page/ranking_page.dart';
import 'package:bilibili/util/color.dart';
import 'package:flutter/material.dart';

class BottomNavigator extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return _BottomNavigator();
  }
}

class _BottomNavigator extends State<BottomNavigator> {
  final _defaultColor = Colors.grey;
  final _activeColor = primary;
  int _currentIndex = 0;
  List<Widget> _pages = [];
  bool _hasBuild = false;
  static int initialPage = 0;
  final PageController _controller = PageController(initialPage: initialPage);

  @override
  Widget build(BuildContext context) {
    _pages = [
      HomePage(onJumpTo: (index) => _onBarTap(index)),
      RangkingPage(),
      FavoritePage(),
      ProfilePage()
    ];
    if (!_hasBuild) {
      _hasBuild = true;
      //页面第一次打开时通知打开的是哪个tab
      HiNavigator.getInstance()
          .onBottomTabChange(initialPage, _pages[initialPage]);
    }

    return Scaffold(
      body: PageView(
        controller: _controller,
        onPageChanged: (index) => _onPageChanged(index),
        physics: NeverScrollableScrollPhysics(), // 禁止tabbar滑动切换
        children: _pages,
      ),
      bottomNavigationBar: BottomNavigationBar(
          currentIndex: _currentIndex,
          onTap: (index) => _onBarTap(index),
          type: BottomNavigationBarType.fixed, // 标题常驻
          selectedItemColor: _activeColor,
          items: [
            _bottomItem('首页', Icons.home, 0),
            _bottomItem('排行', Icons.local_fire_department, 1),
            _bottomItem('收藏', Icons.favorite, 2),
            _bottomItem('我的', Icons.live_tv, 3)
          ]),
    );
  }

  _onBarTap(index) {
    _controller.jumpToPage(index);
    setState(() {
      _currentIndex = index;
    });
  }

  _onPageChanged(index) {
    HiNavigator.getInstance().onBottomTabChange(index, _pages[index]);
  }

  _bottomItem(String title, IconData icon, int index) {
    return BottomNavigationBarItem(
        icon: Icon(
          icon,
          color: _defaultColor,
        ),
        activeIcon: Icon(
          icon,
          color: _activeColor,
        ),
        label: title);
  }
}
